using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Media.Imaging;
using Legacy.Core.SaveGameManagement;

namespace MMXSaveGameConverter
{
    internal sealed class LgsFileReader : FileReaderBase
    {
        private readonly string _lgsPath;

        public LgsFileReader(string lgsPath)
        {
            _lgsPath = lgsPath;
        }

        public override IReaderState Read()
        {
            return new LgsReadState(_lgsPath);
        }

        public override SaveFileMeta ReadFileMeta(IReaderState readerState)
        {
            return new SaveFileMeta(Path.GetFileNameWithoutExtension(_lgsPath));
        }

        public override SaveGameMeta ReadSaveMeta(IReaderState readerState)
        {
            LgsReadState state = (LgsReadState)readerState;
            if (state.SaveMetaReaded)
                throw new InvalidOperationException();

            state.SaveMetaReaded = true;
            BinaryReader br = new BinaryReader(state.LgsInput, Encoding.Default);
            return SaveGame.ReadMetaData(br);
        }

        public override SaveGame ReadSaveGame(IReaderState readerState, SaveGameMeta saveMeta)
        {
            LgsReadState state = (LgsReadState)readerState;
            if (!state.SaveMetaReaded || state.SaveGameReaded)
                throw new InvalidOperationException();

            state.SaveGameReaded = true;
            BinaryReader br = new BinaryReader(state.LgsInput, Encoding.Default);
            SaveGame result = new SaveGame(saveMeta);

            int num = br.ReadInt32();
            for (int index = 0; index < num; index++)
            {
                string str = br.ReadString();
                SaveGameData saveGameData = new SaveGameData(str);
                saveGameData.Read(br);
                result.Add(saveGameData);
            }

            return result;
        }

        public override BitmapFrame ReadScreenshot(IReaderState readerState)
        {
            LgsReadState state = (LgsReadState)readerState;
            if (state.ScreenshotReaded)
                throw new InvalidOperationException();

            PngBitmapDecoder decoder = new PngBitmapDecoder(state.PngInput, BitmapCreateOptions.IgnoreImageCache, BitmapCacheOption.OnLoad);
            return decoder.Frames.First();
        }
    }
}